<?php
namespace Cyfy\Modules\Book\Forms;

use \Cyfy\Modules\Forms;
use \Cyfy\Modules\User\Current;
use \Cyfy\Modules\Book\Module;

/**
 * Editing guest book entry.
 * After submit refreshes page.
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @version 0.1
 */
class EditEntry extends Forms\Form
{
    /**
     * Form structure.
     */
    public function structure()
    {
        $this -> action = "book";
       
        if(Module ::constant('showTitle'))
        {
            $i = new Forms\TextBox("title", Module ::t(120));
            $i -> maxlength = 255;
            $i -> required = true;
            $this -> addItem($i);
        }
        
        $i = new Forms\TextArea("text", Module ::t(130));
        $i -> required = true;
        $this -> addItem($i);
        
        $b = new Forms\Button( Module ::t(240));
        $this -> addButton($b);
        
    }
   
    /**
     * Validating.
     */
    public function validate()
    {
        // permission?
        $eid = $this -> getTemp("eid");
        if(is_numeric($eid))
        {
            $uid = \dibi :: query("SELECT [uid] FROM [:cyfy:Book] WHERE eid = %i", $eid) -> fetchSingle();
            if($uid !== false)
            {
                 // own, or can edit all
                if(\Cyfy\Cyfy ::  permission("Book", "edit all") || (\Cyfy\Cyfy ::  permission("Book", "edit own") && $uid == User :: $uid))
                {
                    return true;
                }
            }else{
                // unknown error
                return false;
            }
        }
        \Cyfy\Message :: set(Module ::t(260), \Cyfy\Message::ERROR);
        return false;
    }
   
    /**
     * Submitting.
     */
    public function submit()
    {
        $assoc = $this -> getAll();
        $assoc["text"] = textWithLinks(nl2br($assoc["text"]));
        \dibi :: query("UPDATE [:cyfy:Book] SET %a", $assoc, "WHERE eid = %i", $this -> getTemp("eid"));
            
        \Cyfy\Message :: set(Module :: t(201, array($this -> get("title"))));
        return true;
    }
}